package com.example.demo.controller;

import com.example.demo.constant.MqConstant;
import com.example.demo.constant.OrderStatus;
import com.example.demo.dao.GoodsDao;
import com.example.demo.dao.OrderDao;
import com.example.demo.entity.Goods;
import com.example.demo.entity.Order;
import com.example.demo.service.MqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class MiaoshaController {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    GoodsDao goodsDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    MqService mqService;


    /**
     * 用户点击立刻抢购按钮，加锁，1.判断商品库存
     * 2.库存大于0生成订单消息并立即扣减库存，生成待支付的订单消息，消费消息创建订单并将状态改为已支付
     */
    @GetMapping("/clickMiaoshaButton/{goodsId}")
    public String clickMiaoshaButton(@PathVariable("goodsId") String goodsId) {
        if (StringUtils.isEmpty(goodsId)) {
            throw new RuntimeException("商品id不能为空");
        }
        int newStock = 0;
        //加锁
        String lockName = "lock:goodsId:" + goodsId;
        RLock lock = redissonClient.getLock(lockName);
        try {
            lock.lock(200, TimeUnit.MILLISECONDS);

            //查询商品的库存
            Goods goods = goodsDao.selectById(goodsId);
            if (null == goods) {
                throw new RuntimeException("商品不存在");
            }
            Integer stock = goods.getStock();
            log.info("查询到当前商品id为{}的库存为{}", goodsId, stock);

            if (stock <= 0) {
                return "lagouPhone已卖完，下次再来吧";
            }

            log.info("开始扣减库存");
            //扣减该商品的库存
            newStock = stock - 1;
            goodsDao.updateById(goods.setStock(newStock));
            log.info("商品id为{}的剩余库存为{}", goodsId, newStock);

            //库存大于0，使用rocketmq生成一条状态为待消费的订单消息
            //封装订单信息并发送
            Order order = new Order().setId(UUID.randomUUID().toString()).setGoodsId(goodsId).setStatus(1).setCrtTime(new Date());
            Message<Order> orderMessage = MessageBuilder.withPayload(order).build();
            mqService.asyncSendOrderInfo(MqConstant.ORDER_TOPIC, orderMessage);
            log.info("商品id为{}向主题{}发送了一条消息：{}", goodsId, MqConstant.ORDER_TOPIC, orderMessage);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread() && lock.isLocked()) {
                lock.unlock();
            }
        }

        return "秒杀成功!!" + "商品id：[" + goodsId + "] 的剩余库存为" + newStock;
    }


    /**
     * 用户支付订单，修改订单的状态为已支付
     */
    @GetMapping("/paidOrder/{orderId}")
    public String paidOrder(@PathVariable String orderId) {

        if (StringUtils.isEmpty(orderId)) {
            throw new RuntimeException("订单id不能为空");
        }

        Order order = orderDao.selectById(orderId);
        order.setStatus(2);
        orderDao.updateById(order);

        return order.toString();
    }
}
